package com.aps.server.service;

import com.aps.common.model.genetic.Order;
import com.aps.common.service.TestGenericService;
import com.aps.server.entity.*;
import com.aps.server.entity.BasicEquip;
import com.aps.server.entity.BasicEquip;
import com.aps.server.mapper.ApsCraftMapper;
import com.aps.server.mapper.ApsOperationMapper;
import com.aps.server.mapper.BasicEquipMapper;
import com.aps.server.mapper.BasicProductMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 设备信息服务类
 * 提供设备信息相关的业务逻辑处理
 */
@Slf4j
@Service
public class BasicEquipService extends TestGenericService {
    @Resource
    BasicEquipMapper basicEquipMapper;
    @Resource
    BasicProductMapper basicProductMapper;
    @Resource
    ApsCraftMapper apsCraftMapper;
    @Resource
    ApsOperationMapper apsOperationMapper;

    /**
     * 创建设备信息
     * 
     * @param basicEquip 设备信息
     * @return 是否创建成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean createEquip(BasicEquip basicEquip) {
        // 自动设置租户ID
        if (basicEquip.getTenantId() == null || basicEquip.getTenantId().trim().isEmpty()) {
            basicEquip.setTenantId(getCurrentTenantId());
        }
        basicEquip.setCreateTime(LocalDateTime.now());
        basicEquip.setUpdateTime(LocalDateTime.now());
        if(StringUtils.isBlank(basicEquip.getEquipCode())) {
            //编码未填写
            return false;
        }
        List<BasicEquip> basicProducts = queryBasicProductByProductCode(Collections.singletonList(basicEquip.getEquipCode()));
        if(CollectionUtils.isEmpty(basicProducts)) {
            //do insert
            int result = basicEquipMapper.insert(basicEquip);
            log.info("创建设备信息结果: {}, 设备ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicEquip.getId(), basicEquip.getTenantId());
            return result > 0;
        }
        log.info("创建设备信息结果: {}, 存在相同的设备code: {}, 租户ID: {}", "失败", basicEquip.getEquipCode(), basicEquip.getTenantId());
        return false;
    }

    //新增、编辑 校验编号是否存在，存在则返回对应 存在的数据
    public List<BasicEquip> queryBasicProductByProductCode(List<String> productCodes) {
        if(CollectionUtils.isEmpty(productCodes)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<BasicEquip> productLambdaQueryWrapper = new LambdaQueryWrapper<BasicEquip>()
                .eq(BasicEquip::getTenantId, getCurrentTenantId())
                .in(BasicEquip::getEquipCode, productCodes);
        return basicEquipMapper.selectList(productLambdaQueryWrapper);
    }
    
    /**
     * 更新设备信息
     * 
     * @param basicProduct 设备信息
     * @return 是否更新成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEquip(BasicEquip basicProduct) {
        basicProduct.setUpdateTime(LocalDateTime.now());
        QueryWrapper<BasicEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", basicProduct.getId()).eq("tenant_id", basicProduct.getTenantId());
        //查询原数据
        List<BasicEquip> basicProductss = basicEquipMapper.selectList(Wrappers.lambdaQuery(BasicEquip.class).eq(BasicEquip::getId, basicProduct.getId()).eq(BasicEquip::getTenantId, basicProduct.getTenantId()));
        BasicEquip original = basicProductss.get(0);
        //编码没变过，直接修改
        if(StringUtils.equals(original.getEquipCode(), basicProduct.getEquipCode())) {
            int result = basicEquipMapper.update(basicProduct, queryWrapper);
            log.info("更新设备信息结果: {}, 设备ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicProduct.getId(), basicProduct.getTenantId());
            return result > 0;
        }
        //变过编码，需要校验一下编码
        List<BasicEquip> basicProducts = queryBasicProductByProductCode(Collections.singletonList(basicProduct.getEquipCode()));
        if(CollectionUtils.isEmpty(basicProducts)) {
            //do insert
            int result = basicEquipMapper.update(basicProduct, queryWrapper);
            log.info("更新设备信息结果: {}, 设备ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicProduct.getId(), basicProduct.getTenantId());
            return result > 0;
        }
        log.info("更新设备信息结果: {}, 存在相同的设备code: {}, 租户ID: {}", "失败", basicProduct.getEquipCode(), basicProduct.getTenantId());
        return false;
    }
    
    /**
     * 删除设备信息
     *
     * @param id 设备ID
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEquip(String id) {
        String tenantId = getCurrentTenantId();
        return deleteEquip(id, tenantId);
    }
    
    /**
     * 根据ID和租户ID删除设备信息
     * 
     * @param id 设备ID
     * @param tenantId 租户ID
     * @return 是否删除成功
     */
    public boolean deleteEquip(String id, String tenantId) {
        QueryWrapper<BasicEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);
        int result = basicEquipMapper.delete(queryWrapper);
        log.info("删除设备信息结果: {}, 设备ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", id, tenantId);
        return result > 0;
    }
    
    /**
     * 根据租户ID查询设备列表
     * @return 设备列表
     */
    public List<BasicEquip> getEquipsByTenantId(String equipCode,String equipName , String equipType) {
        String tenantId = getCurrentTenantId();
        return getProductsByTenantId(tenantId,equipCode,equipName ,equipType);
    }
    
    /**
     * 查询当前租户的设备列表
     */
    public List<BasicEquip> getProductsByTenantId(String tenantId ,String equipCode,String equipName , String equipType) {
        LambdaQueryWrapper<BasicEquip> wrapper = Wrappers.lambdaQuery(BasicEquip.class).eq(BasicEquip::getTenantId, tenantId);
        if(StringUtils.isNotBlank(equipCode)) {
            wrapper.like(BasicEquip::getEquipCode, equipCode);
        }
        if(StringUtils.isNotBlank(equipName)) {
            wrapper.like(BasicEquip::getEquipName, equipName);
        }
        if(StringUtils.isNotBlank(equipType)) {
            wrapper.like(BasicEquip::getEquipType, equipType);
        }
        List<BasicEquip> basicProducts = basicEquipMapper.selectList(wrapper);
        log.info("根据租户ID查询产品列表, 租户ID: {}, 数量: {}", tenantId, basicProducts.size());
        return basicProducts;
    }


    /**
     * 按照订单查询对应产品的工序 通过产品的工序查找对应的设备类型下 的所有设备
     * @param tenantId
     * @param equipCode
     * @param equipName
     * @return
     */
    public List<BasicEquip> getBasicEquipsByTenantIdAndOrders(List<ApsOrder> orders) {

        String tenantId = getCurrentTenantId();
        List<String> productCodes = orders.stream().map(ApsOrder::getProductCode).collect(Collectors.toList());
        LambdaQueryWrapper<BasicProduct> productQ = new LambdaQueryWrapper<BasicProduct>()
                .eq(BasicProduct::getTenantId, getCurrentTenantId())
                .in(BasicProduct::getProductCode, productCodes);
        List<BasicProduct> basicProducts = basicProductMapper.selectList(productQ);
        if(CollectionUtils.isEmpty(basicProducts)) {
            return Collections.emptyList();
        }
        List<String> productIds = basicProducts.stream().map(BasicProduct::getId).collect(Collectors.toList());
        //查找产品对应工艺数据
        LambdaQueryWrapper<ApsCraft> craftsQ = new LambdaQueryWrapper<ApsCraft>()
                .eq(ApsCraft::getTenantId, getCurrentTenantId())
                .in(ApsCraft::getCraftProductId, productIds);
        List<ApsCraft> crafts = apsCraftMapper.selectList(craftsQ);
        if(CollectionUtils.isEmpty(crafts)){
            return Collections.emptyList();
        }
        List<String> craftIds = crafts.stream().map(ApsCraft::getId).collect(Collectors.toList());
        //查询工艺对应工序
        LambdaQueryWrapper<ApsOperation> operationsQ = new LambdaQueryWrapper<ApsOperation>()
                .eq(ApsOperation::getTenantId, getCurrentTenantId())
                .in(ApsOperation::getCraftId, craftIds);
        List<ApsOperation> apsOperations = apsOperationMapper.selectList(operationsQ);
        if(CollectionUtils.isEmpty(apsOperations)){
            return Collections.emptyList();
        }
        List<String> equiptTypes = apsOperations.stream().map(ApsOperation::getOperationEquipType).collect(Collectors.toList());

        //查询工序使用的设备
        LambdaQueryWrapper<BasicEquip> equiptQ = new LambdaQueryWrapper<BasicEquip>()
                .eq(BasicEquip::getTenantId, getCurrentTenantId())
                .in(BasicEquip::getEquipType, equiptTypes);
        return basicEquipMapper.selectList(equiptQ);
    }


    public List<BasicEquip> getBasicEquipsByCodes(List<String> equipCodes) {
        if(CollectionUtils.isEmpty(equipCodes)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<BasicEquip> q = Wrappers.lambdaQuery(BasicEquip.class)
                .eq(BasicEquip::getTenantId,getCurrentTenantId())
                .in(BasicEquip::getEquipCode, equipCodes);
        return basicEquipMapper.selectList(q);
    }
}
